<?php

/**
 * 用户列表
 *
 */
function & li($page_size = ADM_PAGESIZE) {
    global $_TABLES, $class_var;

    $view_var   = array();
    $tbl_link   = $_TABLES['link'];
    $conn       = & get_db_conn();

    $where      = 'WHERE 1 ';
    // 关键字
    $key    = trim(@$_GET['key']);
    $display= @(int)$_GET['display'];
    if($display == 1) {
        $where  .= "AND (display = '1') ";
    } elseif ($display == -1) {
        $where  .= "AND (display = '0') ";
    } else {
    }

    if($key != '') $where  .= "AND (title LIKE '%$key%') ";




    // 分页处理开始
    $csql = "SELECT COUNT(*) AS rs_count FROM $tbl_link $where";
    $rs   = $conn->GetRow($csql);


    $record_total   = @(int)$rs['rs_count'];
    $page_total     = ceil($record_total/$page_size);

    $page   = @(int)$_GET['page'];
    if($page < 1) $page = 1;
    if($page > $page_total && $page_total > 0) $page = $page_total;
    $offset = ($page - 1) * $page_size;
    $limit  = "LIMIT $offset, $page_size";

    $view_var['record_total']   = $record_total;
    $view_var['page_total']     = $page_total;
    $view_var['page']           = $page;
    $view_var['page_size']      = $page_size;
    // 分页处理完毕


    // 列表处理开始
    $order_by   = trim(@$_GET['orderby']);
    $order_desc = @(int)$_GET['desc'];

    $str_order_by   = '';
    if($order_by != '') {
        $order_desc = ($order_desc!=1)?'ASC':'DESC';
        $str_order_by = "`{$order_by}` {$order_desc}, ";
    }

    $sql    = "SELECT * FROM $tbl_link
            $where 
            ORDER BY  $str_order_by id DESC 
            ";
    $rs = $conn->PageExecute($sql,$page_size,$page);
    $view_var['record'] = $rs->GetRows();
    // 列表处理结束


    return $view_var;
}

function read($id = 0) {
    global $_TABLES, $timestamp, $G_big_integer;

    $view_var   = array();
    $tbl_main   = $_TABLES['link'];
    if($id > 0) {
        $conn   = & get_db_conn();
        $sql    = "SELECT * FROM $tbl_main WHERE id = $id ";
        $view_var   = $conn->GetRow($sql);
    } else {
        $view_var   = array(
            'id' => 0,
            'cid' => 0,
            'title' => '',
            'url' => '',
            'img' => '',
            'display'   => 1,
            'createtime'=> $timestamp,
            'hits' => 0,
            'top' => 0,
            'orders' => $G_big_integer
            );
    }
    return $view_var;
}

function request() {
    global $timestamp, $G_big_integer;
    $data = $_POST['link'];


    $data['id']     = @(int)$data['id'];
    $data['cid']    = @(int)$data['cid'];
    $data['display']= @(int)$data['display'];
    $data['delimg'] = @(int)$data['delimg'];
    $data['orders'] = @(int)$data['orders'];
    $data['top']    = @(int)$data['top'];
    if ($data['orders'] >= $G_big_integer || $data['orders'] <= 0) {
        $data['orders'] = $G_big_integer;
    }

    $rule   = array(
        'title' => 'i_string|len:1:100', 
        );
    $def_err    = array(
        'title' => '“友情链接标题”必须填写，并且不能超过100个字符！', 
        );
    $result = data_validator($data, $rule, $def_err);
    if($result !== true) {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        $v, 
                        __FILE__,
                        __LINE__);
        }
    }

    if($GLOBALS['ERR']->Count > 0)
        return false;
    else {
        /**
         * 接受数据前的处理工作，例如上传等
         *
         */
        global $mod, $G_abs_includes;
        require($G_abs_includes . '/upload.php');
        $up = upload_files($mod);

        $data['img'] = '';
        $data['up_img'] = '';
        if(!$data['delimg'] && $up) {
            $data['up_img']= empty($up['img']) ? '' : $up['img'];
        }
        //print_r($data);exit;
        return $data;
    }
}

function not_samerecord($cid, $title, $modify = 0) {
    global $_TABLES;

    $tbl_main   = $_TABLES['link'];
    $conn       = & get_db_conn();
    $where      = '';
    if($modify != 0)  $where = "AND id <> $modify ";

    $rs = $conn->GetRow("SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE title = '$title' AND cid = '$cid' $where ");
    if($rs['rs_count'] > 0) {
        $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                "系统当前分类中已经存在标题为<FONT COLOR=\"red\">{$title}</FONT>的记录，无法当前操作！", 
                __FILE__,
                __LINE__);
        return false;
    }
    return true;
}


function add() {
    global $_TABLES, $timestamp;

    $tbl_link = $_TABLES['link'];
    $tbl_attachments = $_TABLES['attachments'];

    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        if(not_samerecord($result['cid'], $result['title'])) {
            // 没有同名记录，可以进行下一步的工作
            $result['createtime']   = $timestamp;
            if($result['up_img'] == '') {
                $result['img_aid'] = 0;
                $result['img'] = '';
            } else {
                $result['img_aid'] = $result['up_img']['aid'];
                $result['img'] = $result['up_img']['destfile'];
            }
            unset($result['id']);
            if($conn->AutoExecute($tbl_link, $result, 'INSERT')) {
                $id = $conn->Insert_ID();
                // 处理图片
                if($result['img_aid'] > 0) {
                    $conn->Execute("UPDATE $tbl_attachments SET item_id = '$id', upvar = 'img' WHERE aid = '{$result['img_aid']}' ");
                }
                link_cache();
                return $id;
            }
        }
    }
    return false;
}

function modify() {
    global $_TABLES, $timestamp, $mod;

    $tbl_link = $_TABLES['link'];
    $tbl_attachments = $_TABLES['attachments'];
    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        if(not_samerecord($result['cid'], $result['title'], $result['id'])) {
            $updateatt = 0;
            if(@(int)$result['delimg'] == 1) {
                $result['img_aid'] = 0;
                $result['img'] = '';
                $rs  = $conn->GetRow("SELECT img, img_aid FROM $tbl_link WHERE id = '{$result['id']}'");
                $conn->Execute("UPDATE $tbl_attachments SET item_id = 0 WHERE aid = '{$rs['img_aid']}' AND upmod='$mod' AND upvar='img' ");
            } else {
                if($result['up_img'] == '') {
                    // 没有修改图片，不做任何修改工作
                    unset($result['img_aid']);
                    unset($result['img']);
                } else {
                    // 有修改图片，需要重新处理图片
                    // 删除原图片和当前记录之间的关系
                    $rs  = $conn->GetRow("SELECT img, img_aid FROM $tbl_link WHERE id = '{$result['id']}' ");
                    $conn->Execute("UPDATE $tbl_attachments SET item_id = 0 WHERE aid = '{$rs['img_aid']}' AND upmod='$mod' AND upvar='img' ");
                    // 删除完毕


                    $result['img_aid'] = $result['up_img']['aid'];
                    $result['img'] = $result['up_img']['destfile'];
                    $updateatt = 1;
                }
            }
            if($conn->AutoExecute($tbl_link, $result,'UPDATE', 'id=' . $result['id'] )) {
                if($updateatt) {
                    $update_sql = "UPDATE $tbl_attachments SET item_id = '{$result['id']}', upvar = 'img' WHERE aid = '{$result['img_aid']}' ";
                    $conn->Execute($update_sql);
                }
                link_cache();
                return $result['id'];
            }
        }
    }
    return false;
}



function del() {
    global $_TABLES, $mod, $save_flag;
    $tbl_link = $_TABLES['link'];
    $tbl_attachments = $_TABLES['attachments'];

    $deltype    = @(int)$_POST['deltype'];
    if($deltype == $save_flag) {
        // 删除POST传递过来的 item_id 
        // 批量删除
        $str_in = array_join_comma($_POST['item_id']);
    } else {
        // get传递过来的删除 单条删除
        $item_id= @(int)$_GET['item_id'];
        $str_in = $item_id;
    }

    if($str_in != '') {
        $conn   = & get_db_conn();
        // 删除广告图片
        $conn->Execute("UPDATE $tbl_attachments SET item_id = 0 WHERE upmod = '$mod' AND upvar='img' AND item_id IN ($str_in)");
        // 删除广告纪录
        $sql    = "DELETE FROM $tbl_link 
                    WHERE id IN ({$str_in}) ";
        if($conn->Execute($sql)) {
            link_cache();
            js_success('删除指定记录成功！');
        }
    }
}

// 生成缓存
function link_cache() {
    global $_TABLES, $cfg_cache, $link_class, $G_abs_upload, $G_web_upload;

    $tbl_link     = $_TABLES['link'];
    $conn   = & get_db_conn();

    $linkvar= array();
    $sql = "SELECT * FROM $tbl_link WHERE display = 1 ORDER BY cid ASC, top ASC, orders ASC, id ASC ";
    $rs = $conn->Execute($sql);
    if($rs->EOF) {
    } else {
        while (!$rs->EOF) {
            $cid = $rs->fields['cid'];
            $cname = (array_key_exists($cid, $link_class)) ? $link_class[$cid] : '';
            $absimg= $G_abs_upload . '/' . $rs->fields['img'];
            if(file_exists($absimg) && is_file($absimg)) {
                $img = $G_web_upload . $rs->fields['img'];
            } else {
                $img = false;
            }
            $linkvar[]  = array(
                'id'    => $rs->fields['id'],
                'cid'   => $rs->fields['cid'],
                'cname' => $cname,
                'title' => $rs->fields['title'],
                'url'   => $rs->fields['url'],
                'img'   => $img,
                'hits'  => $rs->fields['hits'],
                'site_id'=>$rs->fields['site_id'],
                );
            $rs->MoveNext();
        }
    }

    // 写缓存
    $file_name  = $cfg_cache['cache_abspath'] . '/' . $cfg_cache['link_cache_filename'];
    $str_var    = "<"."?php\r\n" . 
            "\$" . $cfg_cache['link_cache_var'] . " = " . var_export_str($linkvar) . ";\r\n".
            "?".">";
    write_to_file($file_name, $str_var);
}
?>